<template>
  <div class="app-container">

    <!-- 顶部查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
      <el-form-item label="单据时间" prop="documentTime">
        <el-date-picker v-model="queryParams.documentTime" type="daterange" range-separator="至" 
          start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" :default-time="['00:00:00', '23:59:59']"
          :picker-options="{ shortcuts: [{ text: '最近7日', onClick(picker) { const end = new Date(); const start = new Date(); start.setTime(start.getTime() - 3600 * 1000 * 24 * 7); picker.$emit('pick', [start, end]); } }] }"/>
      </el-form-item>
      <el-form-item label="发货单号" prop="deliveryCode">
        <el-input v-model="queryParams.deliveryCode" placeholder="请输入发货单号" clearable/>
      </el-form-item>
      <el-form-item label="店铺名称" prop="shopName">
        <el-select v-model="queryParams.shopName" placeholder="请选择店铺名称" filterable remote clearable
          :remote-method="remoteShopSearch">
          <el-option v-for="item in shopOptions" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="会员名称" prop="memberName">
        <el-input v-model="queryParams.memberName" placeholder="请输入会员名称" clearable/>
      </el-form-item>
      <el-form-item label="平台单号" prop="platformOrderCode">
        <el-input v-model="queryParams.platformOrderCode" placeholder="请输入平台单号" clearable/>
      </el-form-item>
      <el-form-item label="出库状态" prop="outboundStatus">
        <el-select v-model="queryParams.outboundStatus" placeholder="请选择出库状态" clearable>
          <el-option label="全部出库" value="FULLY_OUT"/>
          <el-option label="部分出库" value="PARTIALLY_OUT"/>
          <el-option label="未出库" value="NOT_OUT"/>
        </el-select>
      </el-form-item>
      <el-form-item label="标记状态">
        <el-checkbox-group v-model="queryParams.flags">
          <el-checkbox label="实到打标">实到打标</el-checkbox>
          <el-checkbox label="物流单打标">物流单打标</el-checkbox>
          <el-checkbox label="发货单打标">发货单打标</el-checkbox>
          <el-checkbox label="扫描">扫描</el-checkbox>
          <el-checkbox label="拦截">拦截</el-checkbox>
          <el-checkbox label="发货">发货</el-checkbox>
          <el-checkbox label="外仓缺货">外仓缺货</el-checkbox>
          <el-checkbox label="外仓订单">外仓订单</el-checkbox>
          <el-checkbox label="已转外仓">已转外仓</el-checkbox>
          <el-checkbox label="作废">作废</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="物流公司" prop="expressCompany">
        <el-select v-model="queryParams.expressCompany" placeholder="请选择物流公司" clearable>
          <!-- <el-option v-for="dict in dict.type.express_company" :key="dict.value" :label="dict.label" :value="dict.value"/> -->
        </el-select>
      </el-form-item>
      <el-form-item label="物流单号" prop="expressNumber">
        <el-input v-model="queryParams.expressNumber" placeholder="请输入物流单号" clearable/>
      </el-form-item>
      <el-form-item label="条件备注" prop="remark">
        <el-input v-model="queryParams.remark" placeholder="请输入条件备注" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 功能按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleVoid">作废</el-button>
      </el-col>
    </el-row>

    <!-- 主表格 -->
    <vxe-table
      border
      stripe
      v-loading="loading"
      ref="mainTable"
      size="small"
      header-align="center"
      :data="mainTableData"
      @checkbox-change="mainCheckboxChange"
      @checkbox-all="mainCheckboxAll"
      @cell-click="cellClickEvent"
    >
      <vxe-column type="checkbox" width="60" fixed="left"></vxe-column>
      <vxe-column type="seq" title="序号" width="60" fixed="left"></vxe-column>
      <vxe-column field="isVoid" title="作废" align="center" width="60">
        <template #default="{ row }">
          <el-tag v-if="row.isVoid" type="danger" size="mini">已作废</el-tag>
        </template>
      </vxe-column>
      <vxe-column field="hasLogisticsLabel" title="物流单打标" align="center" width="100">
        <template #default="{ row }">
          <el-tag :type="row.hasLogisticsLabel ? 'success' : 'info'" size="mini">{{ row.hasLogisticsLabel ? '是' : '否' }}</el-tag>
        </template>
      </vxe-column>
      <vxe-column field="hasElectronicBill" title="电子面单" align="center" width="100">
        <template #default="{ row }">
          <el-tag :type="row.hasElectronicBill ? 'success' : 'info'" size="mini">{{ row.hasElectronicBill ? '是' : '否' }}</el-tag>
        </template>
      </vxe-column>
      <vxe-column field="isIntercepted" title="拦截" align="center" width="60">
        <template #default="{ row }">
          <el-tag v-if="row.isIntercepted" type="warning" size="mini">已拦截</el-tag>
        </template>
      </vxe-column>
      <vxe-column field="isScanned" title="扫描" align="center" width="60">
        <template #default="{ row }">
          <el-tag :type="row.isScanned ? 'success' : 'info'" size="mini">{{ row.isScanned ? '是' : '否' }}</el-tag>
        </template>
      </vxe-column>
      <vxe-column field="hasWeightLabel" title="标重" align="center" width="60">
        <template #default="{ row }">
          <el-tag :type="row.hasWeightLabel ? 'success' : 'info'" size="mini">{{ row.hasWeightLabel ? '是' : '否' }}</el-tag>
        </template>
      </vxe-column>
      <vxe-column field="isShipped" title="发货" align="center" width="60">
        <template #default="{ row }">
          <el-tag :type="row.isShipped ? 'success' : 'warning'" size="mini">{{ row.isShipped ? '已发货' : '未发货' }}</el-tag>
        </template>
      </vxe-column>
      <vxe-column field="hasMultiPackage" title="多包裹子母件" align="center" width="120">
        <template #default="{ row }">
          <el-tag v-if="row.hasMultiPackage" type="primary" size="mini">是</el-tag>
        </template>
      </vxe-column>
      <vxe-column field="documentCode" title="单据编号" align="center"></vxe-column>
      <vxe-column field="logisticsCode" title="物流单号" align="center"></vxe-column>
      <vxe-column field="logisticsCompany" title="物流公司" align="center"></vxe-column>
      <vxe-column field="shopName" title="店铺" align="center"></vxe-column>
      <vxe-column field="memberName" title="会员" align="center"></vxe-column>
      <vxe-column field="warehouseName" title="仓库" align="center"></vxe-column>
      <vxe-column field="buyerRemark" title="买家备注" align="center" show-overflow></vxe-column>
      <vxe-column field="sellerRemark" title="卖家备注" align="center" show-overflow></vxe-column>
      <vxe-column field="secondRemark" title="二次备注" align="center" show-overflow></vxe-column>
      <vxe-column field="syncStatus" title="数据同步状态" align="center" width="120">
        <template #default="{ row }">
          <el-tag :type="row.syncStatus === 'SUCCESS' ? 'success' : row.syncStatus === 'FAILED' ? 'danger' : 'info'" size="mini">
            {{ row.syncStatus === 'SUCCESS' ? '成功' : row.syncStatus === 'FAILED' ? '失败' : '未同步' }}
          </el-tag>
        </template>
      </vxe-column>
      <vxe-column field="buyer" title="购货人" align="center"></vxe-column>
      <vxe-column field="receiver" title="收货人" align="center"></vxe-column>
      <vxe-column field="deliveryAddress" title="配送地址" align="center" show-overflow></vxe-column>
      <vxe-column field="deliveryPerson" title="配送人" align="center"></vxe-column>
      <vxe-column field="deliveryTime" title="配送时间" align="center"></vxe-column>
      <vxe-column field="insuranceAmount" title="保价金额" align="center">
        <template #default="{ row }">
          {{ row.insuranceAmount ? '￥' + row.insuranceAmount : '' }}
        </template>
      </vxe-column>
    </vxe-table>

    <!-- 主表格分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 底部Tab区域 -->
    <div class="app-container-footer">
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="订单明细" name="orderDetail">
            <OrderDetail :deliveryOrderId="currentCellId" />
          </el-tab-pane>
          <el-tab-pane label="商品明细" name="itemDetail">
            <ItemDetail :deliveryOrderId="currentCellId" />
          </el-tab-pane>
          <el-tab-pane label="收货信息" name="receiverInfo">
            <ReceiverInfo :deliveryOrderId="currentCellId" />
          </el-tab-pane>
          <el-tab-pane label="包裹信息" name="packageInfo">
            <PackageInfo :deliveryOrderId="currentCellId" />
          </el-tab-pane>
          <el-tab-pane label="订单日志" name="orderLog">
            <OrderLog :deliveryOrderId="currentCellId" />
          </el-tab-pane>
          <el-tab-pane label="操作日志" name="opLog">
            <OpLog :deliveryOrderId="currentCellId" />
          </el-tab-pane>
        </el-tabs>
    </div>
  </div>
</template>

<script>
import OrderDetail from './components/orderDetail.vue';
import ItemDetail from './components/itemDetail.vue';
import ReceiverInfo from './components/receiverInfo.vue';
import PackageInfo from './components/packageInfos.vue';
import OrderLog from './components/orderLog.vue';
import OpLog from './components/opLog.vue';

import { listPrepare } from "@/api/mes/sales/prepare";


export default {
  name: "Prepare",
  components: {
    OrderDetail,
    ItemDetail,
    ReceiverInfo,
    PackageInfo,
    OrderLog,
    OpLog
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        documentTime: [], // 单据时间范围
        deliveryCode: undefined, // 发货单号
        shopName: undefined, // 店铺名称
        memberName: undefined, // 会员名称
        platformOrderCode: undefined, // 平台单号
        outboundStatus: undefined, // 出库状态
        flags: [], // 标记状态复选框组
        expressCompany: undefined, // 物流公司
        expressNumber: undefined, // 物流单号
        remark: undefined, // 条件备注
      },
      // 店铺选项
      shopOptions: [],
      // 主表格数据
      mainTableData: [],
      // 底部Tab
      activeTab: 'orderDetail',
      // 当前选中行ID
      currentCellId: null,

    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 处理作废操作 */
    handleVoid() {
      if (!this.ids || this.ids.length === 0) {
        this.$modal.msgError('请选择要作废的数据');
        return;
      }
      this.$confirm('确认要作废选中的记录吗？', '警告', {
        type: 'warning'
      }).then(() => {
        // TODO: 调用作废接口
        // voidDelivery(this.ids).then(response => {
        //   this.$modal.msgSuccess('作废成功');
        //   this.getList();
        // });
        this.$modal.msgSuccess('作废成功');
        this.getList();
      }).catch(() => {});
    },

    /** 远程搜索店铺 */
    remoteShopSearch(query) {
      if (query) {
        // TODO: 调用店铺搜索接口
        // searchShops(query).then(response => {
        //   this.shopOptions = response.data.map(item => ({
        //     value: item.id,
        //     label: item.name
        //   }));
        // });
        
        // 临时使用模拟数据
        this.shopOptions = [
          { value: '1', label: '店铺A' },
          { value: '2', label: '店铺B' },
          { value: '3', label: '店铺C' }
        ].filter(item => item.label.toLowerCase().includes(query.toLowerCase()));
      } else {
        this.shopOptions = [];
      }
    },

    /** 查询列表 */
    getList() {
      this.loading = true;
      listPrepare(this.queryParams)
        .then(response => {
          // 兼容后端返回格式，假设 response.rows 为数据数组，response.total 为总数
          this.mainTableData = (response.rows || []).map(item => ({
            id: item.id,
            isVoid: item.isVoid,
            hasLogisticsLabel: item.hasLogisticsLabel,
            hasElectronicBill: item.hasElectronicBill,
            isIntercepted: item.isIntercepted,
            isScanned: item.isScanned,
            hasWeightLabel: item.hasWeightLabel,
            isShipped: item.isShipped,
            hasMultiPackage: item.hasMultiPackage,
            documentCode: item.documentCode,
            logisticsCode: item.logisticsCode,
            logisticsCompany: item.logisticsCompany,
            shopName: item.shopName,
            memberName: item.memberName,
            warehouseName: item.warehouseName,
            buyerRemark: item.buyerRemark,
            sellerRemark: item.sellerRemark,
            secondRemark: item.secondRemark,
            syncStatus: item.syncStatus,
            buyer: item.buyer,
            receiver: item.receiver,
            deliveryAddress: item.deliveryAddress,
            deliveryPerson: item.deliveryPerson,
            deliveryTime: item.deliveryTime,
            insuranceAmount: item.insuranceAmount
          }));
          this.total = response.total || 0;
          this.loading = false;
          if (this.mainTableData.length > 0) {
            this.$refs.mainTable.setCurrentRow(this.mainTableData[0]);
            this.cellClickEvent({ row: this.mainTableData[0] });
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 主表格 Checkbox 事件 */
    mainCheckboxChange({ records }) {
      this.ids = records.map(item => item.id);
    },
    mainCheckboxAll({ records }) {
      this.ids = records.map(item => item.id);
    },
    /** 单元格点击事件 */
    cellClickEvent({ row }) {
      if (row && row.id !== this.currentCellId) {
        this.currentCellId = row.id;
      }
    },

  }
};
</script>

<style lang="scss" scoped>
.app-container-footer {
  margin-top: 20px;
}
.mb8 {
  margin-bottom: 8px;
}
</style>
